# -*- coding: utf-8 -*-
# @Time : 2022/5/20 16:51
# @FileName: HoldingPie.py
# @Mail: lizhigen1996@aliyun.com

__author__ = 'Zhigen.li'

import sys
import random
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QColor, QCursor
from PyQt5.QtWidgets import QToolTip, QDialog, QApplication, QGridLayout
from PyQt5.QtChart import QChart, QChartView, QPieSeries, QPieSlice
from Tools.Util import *
from res.resource_rc import *
from Config.Config import CatchExceptions

def getColor():
    color: int
    color1 = random.randint(16, 255)
    color2 = random.randint(16, 255)
    color3 = random.randint(16, 255)
    color1 = hex(color1)
    color2 = hex(color2)
    color3 = hex(color3)
    ans = "#" + color1[2:] + color2[2:] + color3[2:]
    return ans

class HoldingPie(QDialog):
    def __init__(self):
        super(HoldingPie, self).__init__()
        self.resize(1000, 600)
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")

    @CatchExceptions
    def create_piechart(self, name, code, targetNames, targetSecids, rates):
        self.setWindowTitle("{}({})持仓占比".format(name, code))
        series = QPieSeries()

        rate = 0.0
        for idx, n in enumerate(targetNames):
            if rates[idx] > 0.8:
                series.append(n, rates[idx])
                slice = series.slices()[idx]
                slice.hovered.connect(self.onSliceHovered)
                slice.setLabelVisible(True)
                slice.setBrush(QColor(getColor()))
                rate += rates[idx]

        if rate < 100.0:
            els = 100.0 - rate
            series.append('其他', round(els, 2))
            slice = series.slices()[-1]
            slice.hovered.connect(self.onSliceHovered)
            slice.setLabelVisible(True)
            slice.setBrush(QColor(getColor()))

        chart = QChart()
        chart.legend().hide()
        chart.addSeries(series)
        chart.createDefaultAxes()
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.setTitle("{}({})持仓占比".format(name, code))

        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignBottom)

        chartview = QChartView(chart)
        chartview.setRenderHint(QPainter.Antialiasing)
        self.gridLayout.addWidget(chartview)
        self.exec()

    def onSliceHovered(self, b):
        sender = self.sender()
        if b:
            sender.setExploded(True)
            text = '{}\n{}%'.format(sender.label(), sender.value())
            QToolTip.showText(QCursor.pos(), text, self, self.rect(), 2000)
        else:
            sender.setExploded(False)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 初始化所有视图

    targetNames, urls, targetSecids, rates, correlationNames, correlationUrls = equityHoldings('161725')
    login = HoldingPie()
    login.create_piechart('白酒', '161725', targetNames, targetSecids, rates)
    sys.exit(app.exec_())
